﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Dot5Demo
{
    public class AnimateImageCtl : Control
    {

        private AnimateImage anImage;

        public Image Image
        {
            get { return anImage.Image; }
            set
            {
                anImage.SetImage(value);
                if (value != null)
                    ImgSize = value.Size;
            }
        }
        private Size ImgSize;
        private object _lockobj = new object();
        public AnimateImageCtl()
        {
            anImage = new AnimateImage();
            anImage.OnFrameChanged += AnImage_OnFrameChanged;
            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
            this.VisibleChanged += AnimateImageCtl_VisibleChanged;
        }

        public void LoopPlay(bool value)
        {

        }

        public void Play()
        {
            anImage.Play();
        }

        public void Stop()
        {
            anImage.Stop();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            anImage.EnterLock();
            if (anImage.Image != null)
            {
                var x = (this.Width - ImgSize.Width) / 2;
                var y = (this.Height - ImgSize.Height) / 2;
                e.Graphics.DrawImage(anImage.Image, x, y);
            }
            anImage.ExitLock();
        }

        private void AnimateImageCtl_VisibleChanged(object sender, EventArgs e)
        {
            if (Visible)
            {
                anImage.Play();
            }
            else
            {
                anImage.Stop();
            }
        }

        private void AnImage_OnFrameChanged(object sender, EventArgs e)
        {
            this.Invalidate();
        }
    }
}
